﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NexTrackDesktop.Media;
using System.Windows;

namespace NexTrackDesktop.NexTrack
{
    /// <summary>
    /// This class contains nextrack instance and communicates with web service
    /// </summary>
    public class Client
    {        
        public Client(MainServiceAdapter adapter)
        {
    //        string libraryLocation = Path.Combine(
    //Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
    //"NexTrack", "library.xml");

    //        ILibrarySource appDataSource = new LibraryXMLFileSource(libraryLocation);
    //        Library lib = new Media.Library(new TagLibTagger(), appDataSource);

    //        Client Client = new Client(new MainServiceMock());

    //        Client.MediaLibrary = lib;
    //        ViewModelBase.Client = Client;
            WebService = adapter;

            ThumbnailCache = new ThumbnailCache();
            MediaLibrary = new Library(new FileNameTagger());

            Player = new NexTrackPlayer();
            Player.MediaEnded += new Action(Player_MediaEnded);
        }

        public ThumbnailCache ThumbnailCache { get; set; }
        public MainServiceAdapter WebService { get; set; }
        public Party Party { get; private set; }
        public Library MediaLibrary { get; set; }
        public NexTrackPlayer Player { get; private set; }

        public event Action PartyLoaded;
        public event Action MusicStarting;

        /// <summary>
        /// This method loads the party related resources
        /// </summary>
        /// <param name="party">Party to load</param>
        public void LoadParty(string PartyID, string Description, string AccessCode)
        {
            Party = new Party(PartyID, Description, AccessCode, WebService);
            if (PartyLoaded != null)
                PartyLoaded();
        }

        /// <summary>
        /// This method starts the music for the party.
        /// </summary>
        public void StartMusic()
        {
            if (MusicStarting != null)
                MusicStarting();

            NextSong();
        }

        /// <summary>
        /// When the media player's music has ended, we start a new song.
        /// </summary>
        private void Player_MediaEnded()
        {
            NextSong();
        }

        public void NextSong()
        {
            Song s = WebService.GetNextSong();
            Player.NowPlaying = s;
            WebService.UpdateNowPlaying(s);
            Party.Queue.UpdateQueue();
        }

    }
}
